//
//  LGConsultHomeController.m
//  呼吸训练
//
//  Created by 1234 on 2024/5/8.
//


#import "LGConsultHomeController.h"
//通知--团队审批列表
#import "LGTeamApproveController.h"
#import "LGConsultHomeViewCell.h"
#import "LGBottomShadowView.h"
#import "TUICore.h"
#import "TUIConversationListDataProvider.h"
#import "TUIConversationListBaseDataProvider.h"
#import "TUIConversationListControllerListener.h"
#import "TUIConversationCellData.h"
#import <ImSDK_Plus/V2TIMManager.h>
#import "LGNavigationView.h"
#import "TUIChatConfig.h"
#import "TUITextMessageCell.h"
@interface LGConsultHomeController ()<UITableViewDelegate,UITableViewDataSource,V2TIMSimpleMsgListener,TUIConversationListControllerListener>
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)LGBottomShadowView *shadowView;
/**   */
@property (nonatomic , strong)LGNavigationView *navigationView;

//@property (nonatomic, weak) id<TUIConversationListControllerListener> delegate;
//
//@property (nonatomic, strong) TUIConversationListBaseDataProvider *dataProvider;

/**   */
@property (nonatomic , strong)NSArray *dataArray;

@end

@implementation LGConsultHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    LGNavigationView *navigationView = [[LGNavigationView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, topBarHeight)];
    navigationView.titleLabel.text = @"咨询管理";
    [navigationView.backBtn setImage:[UIImage imageNamed:@"通知消息"] forState:UIControlStateNormal];
    [navigationView.backBtn setImage:[UIImage imageNamed:@"通知消息-Select"] forState:UIControlStateSelected];
    [navigationView.backBtn addTarget:self action:@selector(checkNotificationAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationView = navigationView;
    [self.view addSubview:navigationView];
    self.view.bounds = CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight-tabBarHeight);

    //用户头像是圆形
    [TUIConfig defaultConfig].avatarType = TAvatarTypeRounded;
    //聊天窗口背景颜色
    [TUIChatConfig defaultConfig].backgroudColor = [UIColor colorWithString:@"#F6F6F6"];
    [TUIChatConfig defaultConfig].enableWelcomeCustomMessage = NO;//不需要自定义消息
//    [TUITextMessageCell setOutgoingBubble:[UIImage imageNamed:@""]];
//    [TUITextMessageCell setIncommingBubble:[UIImage imageNamed:@""]];

    
    // Do any additional setup after loading the view.
//    [self createSubView];
//    [self.dataProvider loadNexPageConversations];
//    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(onFriendInfoChanged:) name:@"FriendInfoChangedNotification" object:nil];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.dataProvider loadNexPageConversations];
    V2TIMLoginStatus loginStatus = [[V2TIMManager sharedInstance] getLoginStatus];
    if(loginStatus == V2TIM_STATUS_LOGOUT){
        [LGLoginManager loginTencentCloud];
    }
    [[V2TIMManager sharedInstance]addSimpleMsgListener:self];
    
    [self requestData];
    [self requestApproveData];
}


-(void)requestData{
    [RequestUtil withGET:@"/tencent/im/groupList" parameters:@{@"id":kUserId} header:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            NSArray *tempArray = returnData;
            NSMutableDictionary *statusDic = [NSMutableDictionary dictionary];
            for (NSDictionary *tempDic in tempArray) {
                [statusDic setValue:LGNSString(tempDic[@"status"]) forKey:LGNSString(tempDic[@"qqGroupId"])];
            }
            [TUIConfig defaultConfig].statusDic = statusDic;
            [self.tableViewForAll reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

//待审批数据
-(void)requestApproveData{
    [RequestUtil withGET:@"/team/toBeApprove" parameters:@{@"doctorId":kUserId} header:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            NSArray *tempArray = returnData;
            self.navigationView.backBtn.selected = tempArray.count>0?YES:NO;
        }
    } error:^(NSError *error) {
        
    }];
}

//通知 -- 团队审批
-(void)checkNotificationAction{
    LGTeamApproveController *controller = [[LGTeamApproveController alloc]init];
    [self.navigationController pushViewController:controller animated:YES];
}


- (void)onRecvGroupTextMessage:(NSString *)msgID groupID:(NSString *)groupID sender:(V2TIMGroupMemberInfo *)info text:(NSString *)text{
    NSLog(@"收到群文本消息");
    [self requestData];
}

/// 收到群自定义（信令）消息
- (void)onRecvGroupCustomMessage:(NSString *)msgID groupID:(NSString *)groupID sender:(V2TIMGroupMemberInfo *)info customData:(NSData *)data{
    NSLog(@"收到群自定义（信令）消息");
    [self requestData];
}

-(void)tableViewDidSelectCell:(TUIConversationCellData *)data{
    NSDictionary *customeDic = nil;
    if(data.lastMessage.customElem){
        customeDic = [NSJSONSerialization JSONObjectWithData:data.lastMessage.customElem.data options:NSJSONReadingMutableLeaves error:nil];
    }
    [super tableViewDidSelectCell:data];
}

- (void)onFriendInfoChanged:(NSNotification *)notice{
    V2TIMFriendInfo *friendInfo = notice.object;
    if (friendInfo == nil) {
        return;
    }
    for (TUIConversationCellData *cellData in self.dataProvider.conversationList) {
        if ([cellData.userID isEqualToString:friendInfo.userID]) {
            NSString *title = friendInfo.friendRemark;
            if (title.length == 0) {
                title = friendInfo.userFullInfo.nickName;
            }
            if (title.length == 0) {
                title = friendInfo.userID;
            }
            cellData.title = title;
            [self.tableView reloadData];
            break;
        }
    }
}

-(void)setDataArray:(NSArray *)dataArray{
    _dataArray = dataArray;
    
}


-(void)consultBtnAction:(UIButton *)sender{
//    TUIChatConversationModel *model = [[TUIChatConversationModel alloc]init];
//    model.groupID = @"@TGS#1CAMIMMMA";
//    TUIGroupChatViewController *controller = [[TUIGroupChatViewController alloc]init];
//    [controller setConversationData:model];
//    [self.navigationController pushViewController:controller animated:YES];
}

//医生群聊
-(void)enterTheGroupChatRoom:(NSString *)groupId title:(NSString *)title{
//    TUIChatConversationModel *model = [[TUIChatConversationModel alloc]init];
//    model.groupID = groupId;
//    model.title = title;
//    TUIGroupChatViewController *controller = [[TUIGroupChatViewController alloc]init];
//    [controller setConversationData:model];
//    [self.navigationController pushViewController:controller animated:YES];
}



#pragma mark TUIConversationListDataProviderDelegate
- (NSString *)getConversationDisplayString:(V2TIMConversation *)conversation{
    V2TIMMessage *msg = conversation.lastMessage;
    if (msg.customElem == nil || msg.customElem.data == nil) {
        return nil;
    }
    NSDictionary *param = [TUITool jsonData2Dictionary:msg.customElem.data];
    if (param != nil && [param isKindOfClass:[NSDictionary class]]) {
        NSString *businessID = param[@"businessID"];
        if (![businessID isKindOfClass:[NSString class]]) {
            return nil;
        }

        // whether custom jump message
        if ([businessID isEqualToString:BussinessID_TextLink] || ([(NSString *)param[@"text"] length] > 0 && [(NSString *)param[@"link"] length] > 0)) {
            NSString *desc = param[@"text"];
            if (msg.status == V2TIM_MSG_STATUS_LOCAL_REVOKED) {
                if(msg.isSelf){
                    desc = TUIKitLocalizableString(TUIKitMessageTipsYouRecallMessage);
                } else if (msg.userID.length > 0){
                    desc = TUIKitLocalizableString(TUIkitMessageTipsOthersRecallMessage);
                } else if (msg.groupID.length > 0) {
                    /**
                     * 对于群组消息的名称显示，优先显示群名片，昵称优先级其次，用户ID优先级最低。
                     * For the name display of group messages, the group business card is displayed first, the nickname has the second priority, and the user ID has the lowest priority.
                     */
                    NSString *userName = msg.nameCard;
                    if (userName.length == 0) {
                        userName = msg.nickName?:msg.sender;
                    }
                    desc = [NSString stringWithFormat:TUIKitLocalizableString(TUIKitMessageTipsRecallMessageFormat), userName];
                }
            }
            return desc;
        }else if([businessID isEqualToString:BussinessID_GroupCreate] || [param.allKeys containsObject:BussinessID_GroupCreate]) {
            // whether the tips message of creating group
            return [NSString stringWithFormat:@"\"%@\"%@",param[@"opUser"],param[@"content"]];
        }
    }
    return nil;
}

- (void)insertConversationsAtIndexPaths:(NSArray *)indexPaths {
    LGLogFunction;
    if (!NSThread.isMainThread) {
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf insertConversationsAtIndexPaths:indexPaths];
        });
        return;
    }
    [self handleConsultData];
//    self.dataArray = self.dataProvider.conversationList;
//    [UIView performWithoutAnimation:^{
//        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
//    }];
}

- (void)reloadConversationsAtIndexPaths:(NSArray *)indexPaths {
    if (!NSThread.isMainThread) {
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf reloadConversationsAtIndexPaths:indexPaths];
        });
        return;
    }
//    self.dataArray = self.dataProvider.conversationList;
    if (self.tableView.isEditing) {
        self.tableView.editing = NO;
    }
    [self handleConsultData];
//    [UIView performWithoutAnimation:^{
//        [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
//    }];
}

- (void)deleteConversationAtIndexPaths:(NSArray *)indexPaths {
    if (!NSThread.isMainThread) {
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf deleteConversationAtIndexPaths:indexPaths];
        });
        return;
    }
    [self handleConsultData];
//    self.dataArray = self.dataProvider.conversationList;
//    [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}

- (void)reloadAllConversations{
    if (!NSThread.isMainThread) {
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf reloadAllConversations];
        });
        return;
    }
    [self handleConsultData];
//    self.dataArray = self.dataProvider.conversationList;
//    [self.tableView reloadData];
    
//    [[V2TIMManager sharedInstance] getConversation:@"2" succ:^(V2TIMConversation *conv) {
//
//    } fail:^(int code, NSString *desc) {
//
//    }]
}

-(void)handleConsultData{
    NSArray *tempArray = self.dataProvider.conversationList;
    NSMutableArray *dataArray = [NSMutableArray array];
    for (TUIConversationCellData *data in tempArray) {
        [dataArray addObject:data];
//        NSDictionary *customeDic = nil;
//        if(data.cloudCustomData){
//            customeDic = [NSJSONSerialization JSONObjectWithData:data.cloudCustomData options:NSJSONReadingMutableLeaves error:nil];
//        }
//        if(customeDic && [customeDic isKindOfClass:[NSDictionary class]] && [customeDic.allKeys count]>0 && [customeDic.allKeys containsObject:@"customMsg"]){
//            [dataArray addObject:data];
//        }
    }
    self.dataArray = [NSArray arrayWithArray:dataArray];
    [self.tableView reloadData];
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LGConsultHomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    TUIConversationCellData *data = self.dataArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell fillWithData:data];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TUIConversationCellData *data = [self.dataArray objectAtIndex:indexPath.row];
//    NSDictionary *customeDic = nil;
//    if(data.cloudCustomData){
//        customeDic = [NSJSONSerialization JSONObjectWithData:data.cloudCustomData options:NSJSONReadingMutableLeaves error:nil];
//    }
//    if(customeDic && [customeDic isKindOfClass:[NSDictionary class]] && [customeDic.allKeys count]>0 && [customeDic.allKeys containsObject:@"customMsg"]){
//        customeDic = [ObjectTool jsonToObject:customeDic[@"customMsg"]];
//        NSString *appointId = @"";
//        NSString *title = data.title;
//        if(customeDic && [customeDic isKindOfClass:[NSDictionary class]] && [customeDic.allKeys count]>0){
//            appointId = LGNSString(customeDic[@"appointment_id"]);
//            title = LGNSString(customeDic[@"patient"][@"realname"]);
//        }
//        
//        if(data.userID && data.userID.length>0){
//            //单聊
//            TUIChatConversationModel *model = [[TUIChatConversationModel alloc]init];
//            model.title = title;
////            model.conversationID = data.conversationID;
//            model.userID = data.userID;
//            TUIC2CChatViewController *controller = [[TUIC2CChatViewController alloc]init];
//            controller.appointment_id = appointId;
//            [controller setConversationData:model];
//            [self.navigationController pushViewController:controller animated:YES];
//            
//        }else{
//            //群聊
//            TUIChatConversationModel *model = [[TUIChatConversationModel alloc]init];
//            model.title = title;
////            model.conversationID = data.conversationID;
//            model.groupID = data.groupID;
//            TUIGroupChatViewController *controller = [[TUIGroupChatViewController alloc]init];
//            controller.appointment_id = appointId;
//            [controller setConversationData:model];
//            [self.navigationController pushViewController:controller animated:YES];
//        }
//        [self.delegate conversationListController:self didSelectConversation:data];
        
//    }else if (data.userID && [data.userID isEqualToString:self.systemId]){
//        //系统消息
//        
//    }else{
//        NSDictionary *param = @{
//            TUICore_TUIChatService_GetChatViewControllerMethod_TitleKey : data.title ?: @"",
//            TUICore_TUIChatService_GetChatViewControllerMethod_UserIDKey : data.userID ?: @"",
//            TUICore_TUIChatService_GetChatViewControllerMethod_GroupIDKey : data.groupID ?: @"",
//            TUICore_TUIChatService_GetChatViewControllerMethod_AvatarImageKey : data.avatarImage ?: [UIImage new],
//            TUICore_TUIChatService_GetChatViewControllerMethod_AvatarUrlKey : data.faceUrl ?: @"",
//            TUICore_TUIChatService_GetChatViewControllerMethod_ConversationIDKey : data.conversationID ?: @"",
//            TUICore_TUIChatService_GetChatViewControllerMethod_AtMsgSeqsKey : data.atMsgSeqs ?: @[],
//            TUICore_TUIChatService_GetChatViewControllerMethod_DraftKey: data.draftText ?: @""
//        };
//        
//        UIViewController *chatVC = (UIViewController *)[TUICore callService:TUICore_TUIChatService
//                                                                     method:TUICore_TUIChatService_GetChatViewControllerMethod
//                                                                      param:param];
//        [self.navigationController pushViewController:(UIViewController *)chatVC animated:YES];
//    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *rowActions = [NSMutableArray array];
    TUIConversationCellData *cellData = self.dataProvider.conversationList[indexPath.row];
    __weak typeof(self) weakSelf = self;
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:TUIKitLocalizableString(Delete) handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [weakSelf.dataProvider removeConversation:cellData];
    }];
    deleteAction.backgroundColor = RGB(242, 77, 76);
    [rowActions addObject:deleteAction];
    return rowActions;
}

// available ios 11 +
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)) {
    __weak typeof(self) weakSelf = self;
    TUIConversationCellData *cellData = self.dataProvider.conversationList[indexPath.row];
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:TUIKitLocalizableString(Delete) handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        completionHandler(YES);
        weakSelf.tableView.editing = NO;
        [weakSelf.dataProvider removeConversation:cellData];
    }];
    deleteAction.backgroundColor = RGB(242, 77, 76);
    UISwipeActionsConfiguration *configuration = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
    configuration.performsFirstActionWithFullSwipe = NO;
    return configuration;
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.dataProvider loadNexPageConversations];
}


- (void)dealloc{
    [NSNotificationCenter.defaultCenter removeObserver:self];
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
//    self.fd_prefersNavigationBarHidden = YES;
//    self.view.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
//    [self.view addSubview:self.tableView];
//    [self emptyViewWithSuperView:self.view frame:self.tableView.frame];
//    self.emptyView.backgroundColor = [UIColor clearColor];
//    [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无会话" offset:30];
//    [self.view addSubview:self.shadowView];
}

//-(TUIConversationListBaseDataProvider *)dataProvider{
//    if (!_dataProvider) {
//        _dataProvider = [[TUIConversationListDataProvider alloc] init];
//        _dataProvider.delegate = self;
//    }
//    return _dataProvider;
//}



-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight-tabBarHeight-viewPix(8)) style:UITableViewStylePlain];
        [_tableView registerClass:[LGConsultHomeViewCell class] forCellReuseIdentifier:@"cell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = viewPix(70);
        _tableView.cornerRidus = 15;
        _tableView.dataSource = self;
        _tableView.delegate = self;
//        _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(10))];
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(30))];
       
//        NSDictionary *searchExtension = [TUICore getExtensionInfo:TUICore_TUIConversationExtension_GetSearchBar param:@{TUICore_TUIConversationExtension_ParentVC : self}];
//        if (searchExtension) {
//            UIView *searchBar = [searchExtension tui_objectForKey:TUICore_TUIConversationExtension_SearchBar asClass:UIView.class];
//            [searchBar setFrame: CGRectMake(0, 0, self.view.bounds.size.width, 60)];
//            _tableView.tableHeaderView = searchBar;
//        }
    }
    return _tableView;
}

-(LGBottomShadowView *)shadowView{
    if (!_shadowView) {
        _shadowView = [[LGBottomShadowView alloc]initWithFrame:CGRectMake(0, Screen_H-tabBarHeight-20, Screen_W, 20)];
    }
    return _shadowView ;
}


@end
